package com.ruoyi.system.api.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OkHttpUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.InterfaceOperationLog;
import com.ruoyi.system.api.domain.User;
import com.ruoyi.system.api.service.IInterfaceOperationLogService;
import okhttp3.FormBody;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.mapper.StEquipmentAccessoryMapper;
import com.ruoyi.system.api.domain.StEquipmentAccessory;
import com.ruoyi.system.api.service.IStEquipmentAccessoryService;
import com.ruoyi.common.core.text.Convert;

/**
 * 仪器设备附属信息 仪器设备附属信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-03-09
 */
@Service
public class StEquipmentAccessoryServiceImpl implements IStEquipmentAccessoryService 
{

    private static final Logger log = LoggerFactory.getLogger(StEquipmentAccessoryServiceImpl.class);

    @Autowired
    private StEquipmentAccessoryMapper stEquipmentAccessoryMapper;

    /** 接口调用日志 */
    @Autowired
    private IInterfaceOperationLogService iInterfaceOperationLogService;

    /** 配置文件 */
    @Autowired
    private Global global;


    /**
     * 查询仪器设备附属信息 仪器设备附属信息
     * 
     * @param id 仪器设备附属信息 仪器设备附属信息ID
     * @return 仪器设备附属信息 仪器设备附属信息
     */
    @Override
    public StEquipmentAccessory selectStEquipmentAccessoryById(Long id)
    {
        return stEquipmentAccessoryMapper.selectStEquipmentAccessoryById(id);
    }

    /**
     * 查询仪器设备附属信息 仪器设备附属信息列表
     * 
     * @param stEquipmentAccessory 仪器设备附属信息 仪器设备附属信息
     * @return 仪器设备附属信息 仪器设备附属信息
     */
    @Override
    public List<StEquipmentAccessory> selectStEquipmentAccessoryList(StEquipmentAccessory stEquipmentAccessory)
    {
        return stEquipmentAccessoryMapper.selectStEquipmentAccessoryList(stEquipmentAccessory);
    }

    /**
     * 新增仪器设备附属信息 仪器设备附属信息
     * 
     * @param stEquipmentAccessory 仪器设备附属信息 仪器设备附属信息
     * @return 结果
     */
    @Override
    public int insertStEquipmentAccessory(StEquipmentAccessory stEquipmentAccessory)
    {
        stEquipmentAccessory.setCreateTime(DateUtils.getNowDate());
        return stEquipmentAccessoryMapper.insertStEquipmentAccessory(stEquipmentAccessory);
    }

    /**
     * 修改仪器设备附属信息 仪器设备附属信息
     * 
     * @param stEquipmentAccessory 仪器设备附属信息 仪器设备附属信息
     * @return 结果
     */
    @Override
    public int updateStEquipmentAccessory(StEquipmentAccessory stEquipmentAccessory)
    {
        stEquipmentAccessory.setUpdateTime(DateUtils.getNowDate());
        return stEquipmentAccessoryMapper.updateStEquipmentAccessory(stEquipmentAccessory);
    }

    /**
     * 删除仪器设备附属信息 仪器设备附属信息对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStEquipmentAccessoryByIds(String ids)
    {
        return stEquipmentAccessoryMapper.deleteStEquipmentAccessoryByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除仪器设备附属信息 仪器设备附属信息信息
     * 
     * @param id 仪器设备附属信息 仪器设备附属信息ID
     * @return 结果
     */
    @Override
    public int deleteStEquipmentAccessoryById(Long id)
    {
        return stEquipmentAccessoryMapper.deleteStEquipmentAccessoryById(id);
    }

    /**
     *  添加附属设备信息
     *
     * @param equipmentAccessory
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 3:19 下午
     */
    @Override
    public ResponseWithData<?> addEquipmentAccessory(StEquipmentAccessory equipmentAccessory) {
        /** 调用CC端接口 */
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("addInstrumentAsset.asmx/addInstrumentAssetHandle");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        /** POST请求 参数赋值 */
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("InstrumentCode", equipmentAccessory.getInstrumentNo());
        builder.add("Engineer_id", equipmentAccessory.getEnginnerId().toString());
        builder.add("ASSET_SN", equipmentAccessory.getSerialNumber());
        builder.add("ASSET_NAME", equipmentAccessory.getAccessoryName());
       if(StringUtils.isEmpty(equipmentAccessory.getWarrantyStartTime())){
           builder.add("Asset_WarrantyStart", "");
       }else{
           builder.add("Asset_WarrantyStart", equipmentAccessory.getWarrantyStartTime());
       }
        if(StringUtils.isEmpty(equipmentAccessory.getWarrantyEndTime())){
            builder.add("Asset_WarrantyEnd", "");
        }else{
            builder.add("Asset_WarrantyEnd", equipmentAccessory.getWarrantyEndTime());
        }
        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.56新增附属设备接口");
        interfaceOperationLog.setInterfaceType("addEquipmentAccessory");
        interfaceOperationLog.setServiceNo(equipmentAccessory.getServiceNo());
        interfaceOperationLog.setFseId(equipmentAccessory.getEnginnerId().toString());
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setInterfaceRequest(JSONObject.toJSONString(equipmentAccessory));
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数："+interfaceResponseBody;
            log.info("调用CC端返回结果："+interfaceResponseBody);
            if(res.code() == 200){
                interfaceState = "1";
            }else {
                interfaceState = "2";
            }
        }catch (Exception e){
            log.info("调用CC端返回结果："+interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if("0".equals(interfaceState)){
            return new ResponseWithData().success().msg("查询失败 调用CC端获取TL名下工程师接口发生异常").code(202);
        }
        if(res!=null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {

                    JSONArray jsonArr = obj.getJSONArray("record");
                    return new ResponseWithData<>().success().msg("添加成功").code(200);

                }
            }
        }
        return new ResponseWithData<>().success().msg("添加失败").code(201);
//        if (StringUtils.isEmpty(equipmentAccessory.getAccessoryName())) {
//            return new ResponseWithData<>().error().msg("accessoryName cannot be empty");
//        }
//        if (null == equipmentAccessory.getWarrantyStartTime()) {
//            return new ResponseWithData<>().error().msg("warrantyStartTime cannot be empty");
//        }
//        if (null == equipmentAccessory.getWarrantyEndTime()) {
//            return new ResponseWithData<>().error().msg("warrantyEndTime cannot be empty");
//        }
//
//        equipmentAccessory.setDelFlag("0");
//        equipmentAccessory.setCreateTime(new Date());
//        equipmentAccessory.setSyncFlag("0");
//        stEquipmentAccessoryMapper.insertStEquipmentAccessory(equipmentAccessory);
//        return new ResponseWithData<>().success(equipmentAccessory).msg("添加成功").code(200);
    }

    /**
     *  查看附属设备列表
     *
     * @param instrumentNo
     * @param enginnerId
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 3:21 下午
     */
    @Override
    public ResponseWithData<?> selectEquipmentAccessorys(String instrumentNo, String enginnerId, String serviceNo) {
        /** 调用CC端接口 */
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("getInstrumentAsset.asmx/getInstrumentAssetHandle");
        /** POST请求 参数赋值 */
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("InstrumentCode", instrumentNo);
        builder.add("Engineer_id", enginnerId);

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.55获取附属设备接口");
        interfaceOperationLog.setInterfaceType("selectEquipmentAccessorys");
        interfaceOperationLog.setServiceNo(serviceNo);
        interfaceOperationLog.setFseId(enginnerId);
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setInterfaceRequest("instrumentNo="+instrumentNo+",enginnerId="+enginnerId+",serviceNo="+serviceNo);
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数："+interfaceResponseBody;
            log.info("调用CC端返回结果："+interfaceResponseBody);
            if(res.code() == 200){
                interfaceState = "1";
            }else {
                interfaceState = "2";
            }
        }catch (Exception e){
            log.info("调用CC端返回结果："+interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if("0".equals(interfaceState)){
            return new ResponseWithData().success().msg("查询失败 调用CC端获取TL名下工程师接口发生异常").code(202);
        }
        if(res!=null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {

                    JSONArray jsonArr = obj.getJSONArray("record");
                    return new ResponseWithData<>().success(jsonArr).msg("查询成功").code(200);

                }
            }
        }
        return new ResponseWithData<>().success().msg("查询失败").code(201);
//        List<StEquipmentAccessory> datas = stEquipmentAccessoryMapper.selectEquipmentAccessorysByServiceNoAndHelpId(serviceNo, helpId);
//        if (null == datas) {
//            datas = new ArrayList<>();
//        }
//        return new ResponseWithData<>().success(datas).code(200);
    }

    /**
     *  移除附属设备信息
     *
     * @param assetNo 附属设备表主键
     * @param enginnerId 提交的工程师ID
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 3:22 下午
     */
    @Override
    public ResponseWithData<?> removeEquipmentAccessory(String instrumentNo, String enginnerId, String assetNo, String serviceNo) {

        /** 调用CC端接口 */
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("delInstrumentAsset.asmx/delInstrumentAssetHandle");
        /** POST请求 参数赋值 */
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("InstrumentCode", instrumentNo);
        builder.add("Engineer_id", enginnerId);
        builder.add("ASSET_No", assetNo);

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.57删除附属设备接口");
        interfaceOperationLog.setInterfaceType("removeEquipmentAccessory");
        interfaceOperationLog.setServiceNo(serviceNo);
        interfaceOperationLog.setFseId(enginnerId);
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setInterfaceRequest("instrumentNo="+instrumentNo+",enginnerId="+enginnerId+",serviceNo="+serviceNo+",assetNo="+assetNo);
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数："+interfaceResponseBody;
            log.info("调用CC端返回结果："+interfaceResponseBody);
            if(res.code() == 200){
                interfaceState = "1";
            }else {
                interfaceState = "2";
            }
        }catch (Exception e){
            log.info("调用CC端返回结果："+interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if("0".equals(interfaceState)){
            return new ResponseWithData().success().msg("查询失败 调用CC端获取TL名下工程师接口发生异常").code(202);
        }
        if(res!=null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {

                    JSONArray jsonArr = obj.getJSONArray("record");
                    return new ResponseWithData<>().success(jsonArr).msg("删除成功").code(200);

                }
            }
        }
        return new ResponseWithData<>().success().msg("删除失败").code(201);

//        StEquipmentAccessory stEquipmentAccessory = stEquipmentAccessoryMapper.selectStEquipmentAccessoryById(id);
//        if (null != stEquipmentAccessory) {
//            stEquipmentAccessory.setDelFlag("2");
//            stEquipmentAccessory.setUpdateBy(enginnerId.toString());
//            stEquipmentAccessory.setUpdateTime(new Date());
//            stEquipmentAccessoryMapper.updateStEquipmentAccessory(stEquipmentAccessory);
//            return new ResponseWithData<>().success().msg("移除附属设备信息成功").code(200);
//        }
//        return new ResponseWithData<>().error().msg("移除附属设备信息失败, 附属设备信息不存在");
    }
}
